// 定义路由
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

// 导入页面组件
// import Home from "@/views/Home";
// import Topic from "@/views/Topic";
// import Category from "@/views/Category";
// import Car from "@/views/Car";
// import User from "@/views/User";
// import Search from "@/views/Search";
// import ProductDetail from "@/views/ProductDetail";

const routes = [
  { path: "/", redirect: "/home" },
  {
    path: "/home",
    component: () => import("@/views/Home"),
    name: "home",
    meta: {
      isshowtanbar: true, // meta 路由原信息
    },
    children: [
      {
        path: "search",
        component: () => import("@/views/Search"),
        meta: {
          isshowtanbar: false,
        },
      },
      {
        path: "channel",
        component: () => import("@/views/Channel"),
        name:'channel',
        meta: {
          isshowtanbar: false,
        },
      },
    ],
  },
 
  {
    path: "/topic",
    component: () => import("@/views/Topic"),
    name: "topic",
    meta: {
      isshowtanbar: true,
    },
  },
  {
    path: "/category",
    component: () => import("@/views/Category"),
    name: "category",
    meta: {
      isshowtanbar: true,
    },
  },
  {
    path: "/car",
    component: () => import("@/views/Car"),
    name: "car",
    meta: {
      isshowtanbar: true,
    },
  },
  {
    path: "/user",
    component: () => import("@/views/User"),
    name: "user",
    meta: {
      isshowtanbar: true,
    },
  },
  {
    path: "/productDetail",
    component: () => import("@/views/ProductDetail"),
    name: "productDetail",
    meta: {
      isshowtanbar: false,
    },
  },
];

// 如下代码解决路由重复点击报错  (该报错vue-router3有  vue-router4没有)
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

// 创建路由实例对象
let router = new VueRouter({
  mode: "history",
  routes,
});

// 创建路由导航前置守卫
// 监控全局所有路由导航,项目中只要需要路由,就会执行守卫
router.beforeEach((to, from, next) => {
  // 判断当访问购物车页时,用户是否登录,未登录跳转到user页
  if (to.path == "/car") {
    // 表示访问购物车页
    let token = localStorage.getItem("token"); //返回值 字符串 或 null
    if (token) {
      // 说明本地有token 是登录状态
      next();
    } else {
      // 说明本地没有token
      // 提示跳转到登录页
      Vue.prototype.$dialog
        .confirm({
          title: "您未登录",
          message: "需要登录请点击确定",
          // theme: 'round-button',
        })
        .then(() => {
          next("/user");
        })
        .catch(() => {
          //点击取消
        });
    }
  } else {
    next();
  }
});

export default router;
